package com.sk.waste.app.activitys

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.lc.smc.lib.views.pulllayout.SKPullRefresh
import com.lc.smc.lib.views.pulllayout.SKPullRefreshLayout
import com.sk.waste.app.R
import com.sk.waste.app.adapters.SpaceAdapter
import com.sk.waste.app.adapters.TenderAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.MerchantlModel
import com.sk.waste.app.models.SpaceModel
import com.sk.waste.app.models.TenderModel
import com.sk.waste.app.utils.OkHttpUtil
import com.sk.waste.app.views.SkAlertDialog
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException

/**
 *  @time 2025/4/25  17:11
 *  @desc 我的发布
 */
class MyPushActivity : BaseActiivity() {

    @LCBindView(R.id.ac_comment_recyclerview)
    private lateinit var recyclerView: RecyclerView

    @LCBindView(R.id.ac_swipe_refreshLayout)
    private var pullRefreshLayout: SKPullRefreshLayout? = null

    private lateinit var mAdapter: SpaceAdapter
    private var merchantList = ArrayList<SpaceModel>()

    private var currentPage = 1
    val userinfo = MyApplication.instance.getUserInfo()

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_list_refresh)
        super.onCreate(savedInstanceState)
        setBack()
        setTitleView("我的发布")
    }

    override fun setListener() {
        pullRefreshLayout!!.onStartListener = refreshListener
        pullRefreshLayout!!.onStartListener.onStartRefresh(pullRefreshLayout)
        recyclerView.layoutManager = LinearLayoutManager(mContext)
        mAdapter = SpaceAdapter(mContext, 0, merchantList, mOnItemClickListener)
        recyclerView.adapter = mAdapter
    }

    private val mOnItemClickListener = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            val position = args[0] as Int
            val intent = Intent(mContext, PushDetailActivity::class.java)
            intent.putExtra("extral_pushid", merchantList[position].id)
            startActivity(intent)
        }

    }

    private val refreshListener = object : SKPullRefresh.OnStartListener {
        override fun onStartRefresh(p0: SKPullRefresh?) {
            currentPage = 1
            getMerchantList()
        }

        override fun onStartLoadmore(p0: SKPullRefresh?) {
            currentPage++
            getMerchantList()
        }
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 空间列表
     *  @param url
     */
    private fun getMerchantList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_SPACE_MYLIST
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("pageSize", AppConfig.PAGE_SIZE)
        params.put("pageNo", currentPage)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                freshOrLoadFaild()
                LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    if (currentPage == 1) {
                        merchantList.clear()
                    }
                    if (success) {
                        val data = jsonObject.getJSONObject("data")
                        val rows = data.getJSONArray("rows")
                        runOnUiThread {
                            fresOrLoadSuccess(rows.length())
                            for (index in 0 until rows.length()) {
                                val item = SpaceModel().apply { getModelInfo(rows.getJSONObject(index)) }
                                val imgArray = rows.getJSONObject(index).getJSONArray("imageList")
                                for (i in 0 until imgArray.length()) {
                                    item.imgList.add(imgArray.getJSONObject(i).getString("imageUrl"))
                                }
                                merchantList.add(item)
                            }
                            mAdapter.notifyDataSetChanged()
                        }
                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        freshOrLoadFaild()
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    freshOrLoadFaild()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                    Log.e("LCLOG_ERROR", e.toString())
                }
            }
        })
    }

    private fun fresOrLoadSuccess(rows: Int) {
        if (1 == currentPage) { // 刷新
            pullRefreshLayout!!.refreshSuccess()
            merchantList.clear()
        } else {
            pullRefreshLayout!!.loadmoreSuccess()
        }
        if (rows == AppConfig.PAGE_SIZE) {
            pullRefreshLayout!!.isLoadmoreable = true
        } else {
            pullRefreshLayout!!.isLoadmoreable = false
        }
    }

    private fun freshOrLoadFaild() {
        runOnUiThread {
            if (currentPage == 1) {
                //            pullRefreshLayout.stopRefresh()
                //                pullRefreshLayout.refreshSuccess();
                pullRefreshLayout!!.refreshFailed();
            } else {
                //                pullRefreshLayout.loadmoreSuccess()
                pullRefreshLayout!!.loadmoreFailed()
            }
        }
    }
}